<?php

class BaseAction implements ezcWorkflowServiceObject 
{
	protected $name;
	protected $cmd;
    protected $cost;
	private $retryTimes;
	private $out;
	private $statusPath;
	private $resultPath;
	
	public function __construct($name, $cmd, $retryTimes=3) {
		$this->name = $name;
		$this->cmd = $cmd;
		$this->retryTimes = $retryTimes;
		
        $this->out = array();
	}
	
	public function execute(ezcWorkflowExecution $execution)
	{
        $startTime = time();
		$runtime = getenv( 'RUNTIME');
		$this->statusPath = $runtime . "/log/{$this->name}.log";
        $this->resultPath = $runtime . "/output/{$this->name}.out";
		$this->cmd = $this->cmd . " >{$this->resultPath} 2>{$this->statusPath}";
		for($i = 0; $i < $this->retryTimes; $i++) {
            Yii::log('execute cmd: '. $this->cmd, CLogger::LEVEL_INFO, EXECUTOR_LOG);
            exec($this->cmd, $this->out, $retVal);

            if(!in_array($retVal, array(0))) {
                Yii::log("execute command error[$retVal], retry...", CLogger::LEVEL_ERROR, EXECUTOR_LOG);
                sleep(5*($i + 1));
            }
            else {
                break;
            }
        }

        $this->cost = time() - $startTime;
        return $retVal == 0 ? true : false;
	}
	
	protected function concreteParams($cmd, $params) {
    	foreach($params as $key => $value) {
            $cmd = str_replace($key, $value, $cmd);
        }
		return $cmd;
    }

	public function getName() {
    	return $this->name;
    }
    
    public function getCmd() {
    	return $this->cmd;
    }
    
    public function getCost() {
        return $this->cost;
    }

	public function getStatus() {
		return file_get_contents($this->statusPath);
    }

    public function getResultSize() {
		return filesize($this->resultPath);
    }
    
    public function getResultCount() {
		return count($this->getResult());
    }
    
    public function getResult() {
		return file($this->resultPath);
    }
    
    public function getResultPath() {
    	return $this->resultPath;
    }
	
	public function __toString()
	{
		return $this->name;
	}
}
